<?php
/*
 * Remember Me functionality is stored in the database and controlled here
 *
 * @author Chris Lunsford
 */
class RememberMe extends Model {

	function __construct() {
		parent::__construct();
		$this->load->helper('date');
	}
	
	/*
	 * Add a new remember me entry to the database
	 * @param array contains username, usernamehash, randomstring, origin time
	 */
	function addRememberMe($data) {
		$this->db->insert('rememberme', $data);
	}
	
	/*
	 * Remove remember me based on username hash and random string
	 *
	 * @param string sha1 hash of username
	 # @param string randomized string of characters
	 */
	function removeRememberMe($hash, $string) {
		$this->db->where('usernamehash', $hash);
		$this->db->where('random_string', $string);
		
		$this->db->limit(1);  //in case user logs in twice and is given the same random string
		
		$this->db->delete('rememberme');
	}
	
	/*
	 * Check to see if a remember me exists for a user
	 *
	 * @param string sha1 hash of username
	 * @param string randomized string of characters
	 * @return string/boolean returns the username if true, FALSE otherwise
	 */
	function checkRememberMe($hash, $string) {
		$this->db->where('usernamehash', $hash);
		$this->db->where('random_string', $string);
		
		$result = $this->db->get('rememberme');
		if ($result->num_rows() > 0) {
			$username = $result->row()->username;
			//check to see if that remember me has expired..if it has, they'll have to log in again next time
			$this->clearOldRememberMe($username);
			
			return $username;
		} else {
			return FALSE;
		}
	}
	
	/*
	 * Clears out an old remember me, if expired (Expiration time set in config)
	 * 
	 * @param string username to clear remember me for
	 */
	function clearOldRememberMe($username) {
		$this->db->where('username',$username);
		$this->db->where('origin_time <',time()-$this->config->item('remember_me_life'));
		$this->db->delete('rememberme');
	}
	
	/*
	 * Garbage collection for old Remember Me - for any user
	 * Expiration time set in config
	 */
	function clearAllOldRememberMe() {
		$this->db->where('origin_time <',time()-$this->config->item('remember_me_life'));
		$this->db->delete('rememberme');
	}	
}
?>